from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import User
from utils.encrypt import md5
from django.shortcuts import redirect
from django.urls import reverse
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from io import BytesIO


# Create your views here.
def index(request):
    return render(request, 'myadmin/index/index.html')


# 登录
def login(request):
    return render(request, 'myadmin/index/login.html')


# 执行登录
def dologin(request):
    try:
        # 验证码校验
        code = request.POST['code']
        # print(code)
        # print(request.session['verifycode'])
        if code != request.session['verifycode']:
            context = {'info': '验证码错误'}
            return render(request, 'myadmin/index/login.html', context)

        username = request.POST['username']
        user = User.objects.get(username=username)
        # 判断是否是管理员
        if user.status == 6:
            # 判断密码是否相同
            password = request.POST['password'] + str(user.password_salt)
            # 拿到密码加盐后再加密
            passwords = md5(password)
            # print(passwords)
            # 判断密码是否正确
            if passwords != user.password_hash:
                context = {'info': '账号密码错误'}
                return render(request, 'myadmin/index/login.html', context)
            else:
                # 成功后写入session中 并重定向到后台首页
                request.session['adminuser'] = user.toDict()  # 对象转字典
                return redirect(reverse('myadmin_index'))
        else:
            context = {'info': '无效的账号【该账号不是管理员'}
            return render(request, 'myadmin/index/login.html', context)
    except Exception as arr:
        print(arr)
        context = {'info': '账号不存在'}
        return render(request, 'myadmin/index/login.html', context)


# 退出登录
def logout(request):
    del request.session['adminuser']
    return redirect(reverse('myadmin_login'))


def check_code(request, width=120, height=30, char_length=5, font_file='static/FZSTK.ttf', font_size=28):
    code = ''

    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')

    def rndChar():
        """
        生成随机字母
        :return:
        """
        return chr(random.randint(65, 90))

    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    # 写文字
    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        # code.append(char)
        code = code + char
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndColor())

    print(code)
    # 写到session中
    request.session['verifycode'] = code
    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())

    # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    # 画干扰线
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)

        draw.line((x1, y1, x2, y2), fill=rndColor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    # 内存文件操作
    stream = BytesIO()
    # 将图片保存到内存中
    img.save(stream, 'png')
    # 返回给浏览器
    return HttpResponse(stream.getvalue(), 'image/png')
